<template>
	<view class="merchantInto">
        <view v-if="parentInfo != ''">
            <SRV-topbar title="店铺入驻" :isLeft="true"></SRV-topbar>
            <view class="line">
                <view class="left">邀请业务员：</view>
                <view class="right">{{parentInfo}}</view>
            </view>
            <!-- <view class="line">
                <view class="left">结算折扣：</view>
                <view class="right">{{formData.merchantRatio}}%</view>
            </view> -->
            <view class="line">
                <view class="left"><span>*</span>店铺名称：</view>
                <view class="right">
                    <input type="text" v-model="formData.title"  value="" placeholder="请输入商店名称" />
                </view>
            </view>
            <view class="line">
                <view class="left"><span>*</span>联系人：</view>
                <view class="right">
                    <input type="text" v-model="formData.name"  value="" placeholder="请输入联系人姓名" />
                </view>
            </view>
            <view class="line">
                <view class="left"><span>*</span>手机号：</view>
                <view class="right">
                    <input type="number" v-model="formData.mobile" value="" placeholder="请输入手机号码" />
                </view>
            </view>
            <view class="line" style="border-bottom: none;padding-bottom: 0;">
                <view class="left"><span>*</span>店铺位置：</view>
                <view class="right">
                    <input type="text" disabled v-model="formData.address_name"  @click="getMapLocation()"/>
                </view>
            </view>
            <view class="line">
                <textarea  v-model="formData.address_details" value="" placeholder="请填写详细地址，不少于5个字" />
            </view>
            <view class="line" style="border-bottom: none;padding-bottom: 0;">
                <view class="left">店铺公告：</view>
            </view>
            <view class="line">
                <textarea  v-model="formData.description" value="" placeholder="请填写店铺公告" />
            </view>
            <view class="line">
                <view class="imgTd">
                    <view><span>*</span>营业执照</view>
                    <image :src="formData.logoUrl" mode="aspectFill" @click="chooseImage('logo', 1)"></image>
                </view>
                <view class="imgTd" style="border-right: none;">
                    <view><span>*</span>门店照</view>
                    <image :src="formData.coverUrl" mode="aspectFill" @click="chooseImage('cover', 1)"></image>
                </view>
            </view>
            <view class="line" style="border-bottom: none;padding-bottom: 0;">
                <view class="left" style="width: 33%;">收款银行信息：</view>
            </view>
            <view class="line">
                <textarea  v-model="formData.bankInfo" value="" placeholder="示例：张三 工商银行 深圳福田支行 0000 0000 0000 0000" />
            </view>
            <!-- <view class="photos">
                <view class="photo_list" v-for="(uploadItem,index) in coversList" :key="index">
                    <image :src="uploadItem.thumbUrl" mode="aspectFill" @tap="previewImage"
                        :data-src="uploadItem.imgUrl" :data-id="index"></image>
                    <image @click="delImg(index)"
                        src="https://app.chinasrv.com/attachment/xcx/icon/del-new.png" class="del"
                        mode="aspectFill"></image>
                </view>
                <image src="https://app.chinasrv.com/attachment/xcx/icon/addphoto.png" mode="aspectFill"
                    @click="chooseImage(1)"></image>
            </view> -->
            <view class="deal">
                <view :class="isclick?'sel':'nosel'" @click="isclick = !isclick"></view>
                <text @click="isclick = !isclick">已阅读，并同意</text>
                <text @click="jump('applyAgreement', 'markteing_explain')">《入驻协议》</text>
            </view>
            <view class="bottom" @click="save">申请入驻</view>
        </view>
        <view v-else>
            <SRV-topbar title="自营店铺" :isLeft="true"></SRV-topbar>
            <div class="content">
            	<div class="list" v-if="nowList.length > 0">
            		<div class="item" v-for="(item,index) in nowList" :key="index" @click="jump('merchantShopInfo', 'id='+item.id)">
            			<div class="left">
            				<image :src="item.picture"></image>
            			</div>
            			<div class="right">
            				<view class="right_con">
            					<text class="oneline name">{{item.title}}</text>
            				</view>
            				<view class="right_con" style="font-size: 28rpx;color: #444444;">{{item.cate_name}}</view>
            				<view class="right_con">
            					<uni-rate disabled="true" :value="item.desc_credit" size="12"></uni-rate>
            					<text class="rate">{{item.desc_credit}}</text>
            					<text class="km">{{ item.distance }}KM</text>
            				</view>
            				<view class="right_con right_con_disc">{{item.desc}}</view>
            			</div>
            		</div>
            	</div>
            </div>
        </view>
    </view>
</template>

<script>
	var _self;
	import pickRegions from '@/components/pick-regions/pick-regions.vue';
	import serve from '../static/request.js';
	import storage from '../static/appkey.js';
	import common from '../static/jump.js';
	import wechatPay from '../static/wechatPay.js';
	export default {
		components: {
			pickRegions
		},
		data() {
			return {
				formData: {
					appkey: uni.getStorageSync('appkey'),
					'access-token': uni.getStorageSync('access-token'),
					parentKey: '',
					title : '',
					name: '',
					mobile: '',
                    address_name: '请点击选择地图',
					address_details: '',
					longitude: '',
					latitude: '',
                    coverUrl: 'https://hdsq.aoorange.cn/attachment/xcx/icon/addphoto.png',
                    cover: '',
					logoUrl: 'https://hdsq.aoorange.cn/attachment/xcx/icon/addphoto.png',
                    logo: '',
                    description: '',
                    bankInfo: '',
                    merchantRatio: '',
                    baseRatio: '',
                    addRatio: '',
				},
                parentInfo: '',
				isSubmit: false,
				isclick: false,
				isLoad: false,
				logoUrl: '',
				coversList: [],
				imgList: [],
                nowList: [],
			}
		},
		methods: {
			getMapLocation(){
				_self.isLoad = true;
				wx.chooseLocation({
					'longitude': _self.formData.longitude,
					'latitude': _self.formData.latitude,
					success:(res)=> {
                        const locationObj = res.address;
                        const provinceRegex = /^(.*?[省|自治区|特别行政区])/;
                        const provinceMatch = locationObj.match(provinceRegex);
                        const province = provinceMatch ? provinceMatch[1] : '';
                        const cityRegex = new RegExp(province+'(.*?市)');
                        const cityMatch = locationObj.match(cityRegex);
                        const city = cityMatch ? cityMatch[1] : '';
                        const districtRegex = new RegExp(city+'(.*?区)');
                        const districtMatch = locationObj.match(districtRegex);
                        const area = districtMatch ? districtMatch[1] : '';
                        _self.formData.address_name = province + " "+city+" "+area;
						_self.formData.address_details = res.name;
						_self.formData.longitude = res.longitude;
						_self.formData.latitude = res.latitude;
						_self.$forceUpdate();
						// this.getRegionFn(res);
					},
					fail:()=>{
						// 如果用uni.chooseLocation没有获取到地理位置，则需要获取当前的授权信息，判断是否有地理授权信息
						uni.getSetting({
							success: (res) => {
								var status = res.authSetting;
								if(!status['scope.userLocation']){
								// 如果授权信息中没有地理位置的授权，则需要弹窗提示用户需要授权地理信息
									uni.showModal({
										title:"是否授权当前位置",
										content:"需要获取您的地理位置，请确认授权，否则地图功能将无法使用",
										success:(tip)=>{
											if(tip.confirm){
											// 如果用户同意授权地理信息，则打开授权设置页面，判断用户的操作
												uni.openSetting({
													success:(data)=>{
													// 如果用户授权了地理信息在，则提示授权成功
														if(data.authSetting['scope.userLocation']===true){
															uni.showToast({
																title:"授权成功",
																icon:"success",
																duration:1000
															})
															// 授权成功后，然后再次chooseLocation获取信息
															uni.chooseLocation({
																success: (res) => {
																	console.log("详细地址",res);
																	// this.getRegionFn(res);
																}
															})
														}else{
															uni.showToast({
																title:"授权失败",
																icon:"none",
																duration:1000
															})
														}
													}
												})
											}
										}
									})
								}
							},
							fail: (res) => {
								uni.showToast({
									title:"调用授权窗口失败",
									icon:"none",
									duration:1000
								})
							}
						})
					}
				});
			},
			getPrepare() {
				serve.request({
					url: '/merchant/apply/prepare',
					data: {
						appkey: uni.getStorageSync('appkey'),
						'access-token': uni.getStorageSync('access-token'),
                        parentKey: this.formData.parentKey,
					},
                    v: '/v3',
				}).then(res => {
					if (res.code == 200) {
						_self.parentInfo = res.data.parentInfo;
                        if(_self.parentInfo == '') {
                            _self.getList();
                            return ;
                        }
                        _self.formData.name = res.data.name;
                        _self.formData.mobile = res.data.mobile;
                        _self.formData.merchantRatio = res.data.ratioInfo.merchantRatio;
                        _self.formData.baseRatio = res.data.ratioInfo.baseRatio;
                        _self.formData.addRatio = res.data.ratioInfo.addRatio;
					} else {
						uni.showToast({
							title: res.message,
							icon: 'none',
							success() {
								setTimeout(function() {
									uni.switchTab({
									    url: '/pages/index/index'
									});
								}, 2000)
							}
						});
					}
				});
			},
			async save() {
				if (_self.isSubmit) {//防止重复提交
					return;
				}
                if(!_self.isclick) {
                    uni.showToast({
                    	title: "请勾选同意协议",
                    	icon: 'none'
                    })
                    return;
                }
				if (_self.formData.title == "") {
					uni.showToast({
						title: "请填写商铺名称",
						icon: 'none'
					})
					return;
				}
				if (_self.formData.name == "") {
					uni.showToast({
						title: "请填写联系人",
						icon: 'none'
					})
					return;
				}
				if (_self.formData.mobile == "") {
					uni.showToast({
						title: "请填写联系电话",
						icon: 'none'
					})
					return;
				}
				if (_self.formData.longitude == "" || _self.formData.latitude == "") {
					uni.showToast({
						title: "请点击地图获取经纬度",
						icon: 'none'
					})
					return;
				}
				if (_self.formData.address == "") {
					uni.showToast({
						title: "请填写详细地址",
						icon: 'none'
					})
					return;
				}
                if (_self.formData.logoUrl == "https://hdsq.aoorange.cn/attachment/xcx/icon/addphoto.png") {
                	uni.showToast({
                		title: "请上传营业执照",
                		icon: 'none'
                	})
                	return;
                }
				if (_self.formData.coverUrl == "https://hdsq.aoorange.cn/attachment/xcx/icon/addphoto.png") {
					uni.showToast({
						title: "请上传门头照",
						icon: 'none'
					})
					return;
				}
				if(_self.formData.logo == '') {
					let uresult = await _self.uploadFileFun(_self.formData.logoUrl);
					if (!uresult) {
					    uni.showToast({
					        title: "营业执照上传失败",
					        icon: 'none'
					    });
					    return;
					}
					_self.formData.logo = uresult;
				}
                if(_self.formData.cover == '') {
                	let uresult = await _self.uploadFileFun(_self.formData.coverUrl);
                	if (!uresult) {
                	    uni.showToast({
                	        title: "门头照上传失败",
                	        icon: 'none'
                	    });
                	    return;
                	}
                	_self.formData.cover = uresult;
                }
                uni.showLoading({
                	title: '提交中···',
                	mask: true
                });
				// if(_self.coversList.length == 0) {
				// 	uni.showToast({
				// 	    title: "请上传门店照片",
				// 	    icon: 'none'
				// 	});
				// 	return;
				// }
				// let imgStr = '';
				// for(let kk = 0; kk < _self.coversList.length; kk ++) {
				// 	let it = _self.coversList[kk];
				// 	if(it.isUpload == 0) {
				// 		let uresult = await _self.uploadFileFun(it.imgUrl);
				// 		if (!uresult) {
				// 		    uni.showToast({
				// 		        title: "门头照第" + (Number(kt) + Number(1)) +"张图片上传失败",
				// 		        icon: 'none'
				// 		    });
				// 		    return;
				// 		}
				// 		it.imgPaht = uresult;
				// 		it.isUpload = 1;
				// 	}
				// 	imgStr += it.imgPaht + ";";
				// }
				// _self.formData.covers = imgStr;
				// _self.formData["access-token"] = '';
				serve.request({
					url: '/merchant/apply/apply',
					data: _self.formData,
                    v: '/v3',
				}, 'POST').then(res => {
                    uni.hideLoading();
					uni.showToast({
						title: res.message,
						icon: 'none',
					});
					if (res.code == 200) {
						uni.redirectTo({
						    url: '/merchant/detail?id='+res.data.id
						});
						return ;
					}
					_self.isSubmit = false;
					
				});
				_self.isSubmit = true;
			},
			getList() {
				serve.request({
					url: '/merchant/merchant/index',
					data: {
                        appkey: uni.getStorageSync('appkey'),
                        'access-token': uni.getStorageSync('access-token'),
                    },
					v: '/v2'
				}).then(res => {
					_self.nowList = res.data;
				});
			},
			chooseImage(type, surplusNum = 1) {
				_self.isLoad = true;
			    uni.chooseImage({
			        count: surplusNum,
			        sizeType: ['original'],
			        sourceType: ['album'],
			        success: (chooseImageRes) => {
			            const tempFilePaths = chooseImageRes.tempFiles;
			            tempFilePaths.forEach((file, key) => {
			                const maxSize = 10 * 1024 * 1024;
			                // console.info("file.size = " + file.size);
			                if (file.size > maxSize) {
			                    uni.showToast({
			                        icon: "none",
			                        title: "文件不能大于10兆",
			                        mask: true,
			                        duration: 1.5e3
			                    });
			                    return;
			                } else {
								if(type == 'logo') {
									_self.formData.logo = '';
									_self.formData.logoUrl = file.path;
									return ;
								}
                                if(type == 'cover') {
                                	_self.formData.cover = '';
                                	_self.formData.coverUrl = file.path;
                                	return ;
                                }
			      //               let temp = {
									// thumbUrl: file.path,
			      //                   imgUrl: file.path,
			      //                   isUpload: 0,
			      //                   imgPath: ''
			      //               };
			      //               _self.coversList.push(temp);
			      //               _self.imgList = [];
			      //               _self.coversList.forEach((it, kt) => {
			      //                   _self.imgList.push(it.imgUrl);
			      //               });
			                }
			            });
			            _self.$forceUpdate();
			        }
			    });
			},
			previewImage: function(e) {
			    var current = e.target.dataset.src;
			    uni.previewImage({
			        current: current,
			        urls: _self.imgList
			    });
			    return;
			},
			delImg(key) {
			    _self.coversList.splice(key, 1);
			    _self.imgList = [];
			    _self.coversList.forEach((it, kt) => {
			        _self.imgList.push(it.imgUrl);
			    });
			    _self.$forceUpdate();
			},
			async uploadFileFun(file) {
			    let accessToken = uni.getStorageSync('access-token');
			    let appkey = uni.getStorageSync('appkey');
			    return new Promise((resolve, reject) => {
			        uni.uploadFile({
			            url: serve.apiUrl() + '/v1/file/images?appkey=' + appkey +
			                '&access-token=' + accessToken,
			            filePath: file,
			            name: 'file',
			            formData: {},
			            success: (uploadFileRes) => {
			                let result = JSON.parse(uploadFileRes.data);
			                console.info(result);
			                if (result.code == 200) {
			                    resolve(result.data.imgPath);
			                } else {
			                    resolve(false);
			                }
			            }
			        });
			    });
			},
			jump(jump_type, jump_link) {
				common.jump(jump_type, jump_link);
			}
		},
		onLoad(option) {
            _self = this;
			_self.formData.parentKey = option.merchantKey || "";
            if(_self.formData.parentKey == "") {
                _self.getList();
            } else {
                _self.getPrepare();
            }
		},
		onPullDownRefresh() {
			console.log('refresh');
			setTimeout(function() {
				uni.stopPullDownRefresh(); //结束下拉加载状态
			}, 1000);
		}
	}
</script>

<style scoped lang="scss">
	.merchantInto{
		padding-bottom: 100upx;
		.main{
			width:100%;
			height:360upx;
		}
		.heng{
			width: 100%;
			height: 12upx;
			background: #F8F8FA;
		}
		.nobottom{
			border: none !important;
		}
		.deal{
			display: flex;
			justify-content: center;
			align-items: center;
			font-size: 24upx;
			padding: 20upx 0upx;
			text:nth-child(2){
				color: #999999;
				margin-left: 11upx;
			}
			text:nth-child(3){
				color: #EB5938;
				margin-left: 11upx;
			}
			.sel {
				background-image: url(https://hdsq.aoorange.cn/attachment/xcx/icon/icon37.png);
				background-repeat: no-repeat;
				width:30upx;
				height:30upx;
				background-size: 100%;
				margin-right: 20upx;
			}
			
			.nosel {
				width: 30upx;
				height: 30upx;
				border: 1upx solid #999999;
				border-radius: 50%;
				margin-right: 20upx;
			}
		}
		.bottom{
			position: fixed;
			bottom: 0;
			width:100%;
			height:100upx;
			line-height: 100upx;
			text-align: center;
			color: #FFFFFF;
			font-size: 28upx;
			background:rgba(255,188,0,1);
			z-index: 9;
		}
		.title{
			color: #666666;
			font-size: 32upx;
			font-weight: bold;
			padding-top: 52upx;
			padding-left: 30upx;
		}
		.line{
			position: relative;
            width: 100%;
            display: flex;
            align-items: center;
            box-sizing: border-box;
            padding: 20rpx;
            border-bottom: 1rpx #EBEBEB solid;
            .left {
                font-size: 32rpx;
                width: 27%;
                text-align: right;
            }
            .right{
                width: 70%;
                input {
                    font-size: 32rpx;
                    border: 1rpx solid #ccc;
                    height: 60rpx;
                    padding-right: 10rpx;
                    padding: 5rpx 20rpx;
                    border-radius: 20rpx;
                    width: 100%;
                }
            }
            
            textarea {
                font-size: 32rpx;
                border: 1rpx solid #ccc;
                height: 100rpx;
                padding-right: 10rpx;
                padding: 20rpx;
                border-radius: 20rpx;
                width: 100%;
            }
        }
		.imgTd {
            width: 50%;
            text-align:center;
            border-right: 1rpx #ebebeb solid;
            image {
                width: 200rpx;
                height: 200rpx;
            }
        }
	}
    .content {
    	.list {
    		.item {
    			display: flex;
    			box-sizing: border-box;
    			align-items: flex-start;
    			padding: 22rpx 32rpx;
    			border-bottom: 1px solid #ebebeb;
    
    			.left {
    				margin-right: 15rpx;
    				image {
    					width: 220rpx;
    					height: 180rpx;
    				}
    			}
    
    			.right {
    				flex: 1;
    				.right_con {
    					display: flex;
    					align-items: center;
    					position: relative;
    					.name {
    						// max-width: 300rpx;
    						font-size: 36rpx;
    					}
    					.state {
    						padding: 5rpx 8rpx;
    						text-align: center;
    						color: #FFFFFF;
    						font-size: 20rpx;
    						border-radius: 2rpx;
    						margin-left: 10rpx;
    					}
    					.rate {
    						color: #FFBC00;
    						font-size: 20rpx;
    						margin-left: 10rpx;
    						margin-top: -9rpx;
    					}
    
    					.km {
    						color: #999999;
    						position: absolute;
    						right: 0rpx;
    						font-size: 20rpx;
    					}
    
    					.discounts {
    						font-size: 20rpx;
    						color: #EB5938;
    						margin-left: 7rpx;
    					}
    				}
    				.right_con_disc{
    					    overflow: hidden;
    					    word-break: break-all;
    					    text-overflow: ellipsis;
    					    display: -webkit-box;
    					    -webkit-box-orient: vertical;
    					    -webkit-line-clamp: 3;
    					    font-size: 28rpx;
    					    white-space: break-spaces;
    					    // height: 116rpx;
    				}
    
    				.right_con:nth-child(2) {
    					padding: 6rpx 0rpx;
    				}
    			}
    		}
    	}
    }
    span {
        color: red;
    }
    .photos {
		    box-sizing: border-box;
		    padding: 30upx 30upx;
		    display: flex;
		    flex-wrap: wrap;
		
		    image {
		        width: 150upx;
		        height: 150upx;
		        border-radius: 10upx;
		        margin-bottom: 20upx;
		    }
		
		    .photo_list {
		        margin-right: 30upx;
		        padding-bottom: 20upx;
		        display: flex;
		        flex-direction: column;
		        align-items: flex-end;
		        position: relative;
		
		        view {
		            color: red;
		            font-size: 30upx;
		        }
		
		        .del {
		            width: 48upx !important;
		            position: absolute;
		            height: 48upx !important;
		            top: -24upx;
		            right: -24upx;
		        }
		    }
		}
</style>